package com.seckill.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    private StringRedisTemplate stringRedisTemplate;
    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    public static final long BEGIN_TIME_TAMP=1640995200L;
    public static final long COUNT_BITS=32;
    //生成全局唯一Id
    public long nextId(String key) {
        //1.获取当前时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond=now.toEpochSecond(ZoneOffset.UTC);
        long time=nowSecond-BEGIN_TIME_TAMP;
        //2.获取当前自增序列 通过redis获取
        //2.1获取当前日期 精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //2.2通过redis自增 每天根据日期更新key就不会出现存储不够的情况
        Long increment = stringRedisTemplate.opsForValue().increment("irc:" + key + date);

        //通过二进制拼接
        return time<<32|increment;
    }

}
